package thread.synchronized_;

/**
 * Created with IntelliJ IDEA
 * Description:线程死锁学习
 * User:22954
 * Date:2024-03-07
 * Time:20:20
 */
public class DeadLock {
    /*
    线程死锁:多个线程互相占用对方的锁,互不相让,造成线程堵塞,形成死锁
            编程中必须避免死锁的发生
     */
    public static void main(String[] args) {
        /*
        线程A对o1上锁,o1要解锁需先获得o2的锁
        但是同时线程B对o2上锁,且o2解锁需获得o1的锁
        最终形成死锁
         */
        DeadLockDemo A = new DeadLockDemo(true);
        DeadLockDemo B = new DeadLockDemo(false);
        A.setName("A");
        B.setName("B");
        A.start();
        B.start();
    }
}

class DeadLockDemo extends Thread {
    static Object o1 = new Object();
    static Object o2 = new Object();
    private boolean flag;

    public DeadLockDemo(boolean flag) {
        this.flag = flag;
    }

    @Override
    public void run() {
        if (flag) {
            synchronized (o1) {
                System.out.println(getName() + " enter 1");
                synchronized (o2) {
                    System.out.println(getName() + " enter 2");
                }
            }
        } else {
            synchronized (o2) {
                System.out.println(getName() + " enter 3");
                synchronized (o1) {
                    System.out.println(getName() + " enter 4");
                }
            }
        }
    }
}
